// pages/addpost/addpost.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    photo: [],
    userInfo: {},
    maintext: "",
    focus: false,
    fileIDs: []
  },

  chooseImages: function () {
    var that = this
    wx.chooseImage({
      count: 4 - that.data.photo.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res)
        var tempFilePath = that.data.photo
        tempFilePath = tempFilePath.concat(res.tempFilePaths)
        that.setData({
          photo: tempFilePath,
          focus: true
        })
      }
    })
  },

  removeImage: function (e) {
    var tempFilePath = this.data.photo
    tempFilePath.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      photo: tempFilePath
    })
  },

  back: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  submit: async function () {
    var that = this
    if (this.data.photo == []) {
      wx.showToast({
        title: '请选择图片',
        icon: 'error',
        duration: 2000
      })
    } else {
      wx.showLoading({
        title: '正在发布',
        mask: true
      })
      
      //上传图片
      let promiseArr = [];
      for (let i = 0; i < this.data.photo.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.photo[i];
          wx.cloud.uploadFile({
            cloudPath: 'discovery/' + new Date().getTime() + '.jpg', // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              });
              console.log(res.fileID) //输出上传后图片的返回地址
              reslove();
            },
            fail: res => {
              wx.showToast({
                title: "上传失败",
              })
            }
          })
        }));
      }
      Promise.all(promiseArr).then(res => { //等数组都做完后做then方法
        console.log(this.data.fileIDs)
        var time = new Date().getTime()
        that.editorCtx.getContents({
          success: function(res) {
            console.log(res.html)
            var maintext_2 = res.html
            wx.cloud.callFunction({
              name: "addpost",
              data: {
                photo:that.data.fileIDs,
                maintext:maintext_2,
                timestamp:time
              }
            }).then(res => {
              console.log(res)
              wx.showToast({
                title: '发布成功',
                duration: 2000
              })
              setTimeout(function () {
                console.log(res.result._id)
                //跳转详情页
                wx.redirectTo({
                  url: '../discoverydetail/discoverydetail?' + 'art=' + res.result._id,
                })
              }, 2000)
            })
          }
        })
      })
      
    }
  },

  onEditorReady() {
    var that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context
    }).exec()
  },

  testsub:function() {
    var that = this
    that.editorCtx.getContents({
      success: function(res) {
        console.log(res.html)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.chooseImages()
    this.setData({
      userInfo: getApp().globalData.userInfo,
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})